package com.ldq.imooc.basics.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author : 李道泉
 * @Description : 基于TCP协议的Socket通信，实现用户登陆服务端
 * @Date : 2018/4/23 15:07
 * @Modified by :
 */
public class TCPServer {

    public static void main(String[] args) {

        try {
            //1、创建ServerSocket对象，绑定端口
            ServerSocket server = new ServerSocket(8888);
            //2、创建监听
            System.out.println("***服务器正在启动，等待客户端连接***");
            Socket socket = server.accept();
            //3、创建输入流读取客户端信息
            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                System.out.println("Server，client001说："+line);
            }
            socket.shutdownInput();

            //4、创建输出流响应客户端请求
            OutputStream os = socket.getOutputStream();
            PrintWriter pw = new PrintWriter(os);
            pw.write("登陆成功，欢迎administrator！");
            pw.flush();

            socket.shutdownOutput();

            //5、关闭相关资源
            pw.close();
            os.close();

            br.close();
            isr.close();
            is.close();
            socket.close();
            server.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
